# coding=utf-8
'''
公共方法
'''
import os
import time,datetime
import yaml
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from common.LoggerUtil import LogUtils


class BasePage:

    def __init__(self, driver):
        self.driver = driver

    def locator(self, loc, timeout=20):
        try:
            WebDriverWait(self.driver, timeout).until(EC.visibility_of_element_located(loc))
            return self.driver.find_element(*loc)
        except Exception as e:
            LogUtils.error(f"点击元素异常：{e}")

    def get_toast(self, loc, timeout=20, poll_frequency=0.5):
        try:
            WebDriverWait(self.driver, timeout, poll_frequency).until(EC.presence_of_element_located(loc))
            return self.driver.find_element(*loc)
        except Exception as e:
            LogUtils.error(f"get_toast-元素异常：{e}")

    def swipe(self, start_x, start_y, end_x, end_y, duration=0):
        # 滑动
        # self.swipe(0.9,0.5,0.3,0.5,1000) 左滑
        window_size = self.driver.get_window_size()
        x = window_size["width"]
        y = window_size["height"]
        self.driver.swipe(start_x=x * start_x,
                          start_y=y * start_y,
                          end_x=x * end_x,
                          end_y=y * end_y,
                          duration=duration
                          )

    # 截图
    def take_screenshot(self, filename):
        screenshots_dir = "./outputs/screenshots"
        if not os.path.exists(screenshots_dir):
            os.makedirs(screenshots_dir)
        timestamp = time.strftime('%Y%m%d%H%M%S')
        folder_name = time.strftime('%Y-%m-%d')
        folder_path = os.path.join(screenshots_dir, folder_name)
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
        screenshot_file = os.path.join(folder_path, f"{filename}_{timestamp}.png")
        self.driver.save_screenshot(screenshot_file)
        return screenshot_file

    def is_element_present(self, by, locator):
        try:
            self.driver.find_element(by=by, value=locator)
            return True
        except NoSuchElementException:
            return False

    def loadStep(self, po_path, key, timeout=20, **kwargs):
        '''读取yaml用例'''
        file = open(po_path, 'r', encoding='utf-8')
        po_data = yaml.safe_load(file)  # 从YAML文件中加载数据
        po_method = po_data[key]  # 获取指定key对应的测试步骤
        # 在loadStep方法中直接读取YAML文件中的test_data并进行自动替换
        LogUtils.info('---开始执行用例：%s---', key)
        for step in po_method:  # 遍历测试步骤
            try:
                action = str(step['action']).lower()  # 这里把action的值转化成了小写
                comment = step.get('code_mit', '')  # 读取注释信息
                LogUtils.info('----%s_用例执行：%s----', comment, step)
                # 处理滑动操作
                if action == "swipe":
                    start_x = float(step['start_x'])
                    start_y = float(step['start_y'])
                    end_x = float(step['end_x'])
                    end_y = float(step['end_y'])
                    duration = int(step.get('duration', 0))  # 如果没有定义duration，则默认为0
                    self.swipe(start_x, start_y, end_x, end_y, duration)
                # 控制 回车键 66
                elif action == "keycode_enter":
                    keycode = int(step['keycode'])
                    self.driver.press_keycode(keycode)
                else:
                    # 点击、输入元素
                    WebDriverWait(self.driver, timeout).until(
                        EC.visibility_of_element_located((step['by'], step['locator'])))
                    element = self.driver.find_element(by=step['by'], value=step['locator'])
                    if action == "click":  # 写上小写，yaml文件中也要写上小写
                        element.click()
                    elif action == "sendkeys":  # 这里要写小写，ymal文件中也要写上小写
                        text = str(step['text'])
                        LogUtils.info("---update_to text：%s" % (text))
                        for k, v in kwargs.items():  # 遍历kwargs中的键值对
                            text = text.replace("$%s" % str(k), str(v))  # 用kwargs中的值替换text中的占位符
                        LogUtils.info("---update text：%s" % (text))
                        element.send_keys(text)
                    else:
                        LogUtils.error("===未知的命令：%s===" % step)
                LogUtils.info('---%s_用例执行完成：%s---', comment, step)
            except Exception as e:
                LogUtils.error(f"{comment}---执行步骤{step}时发生异常：{e}")
                # LogUtils.error("----执行步骤{}时发生异常：{}".format(step, e))
                self.take_screenshot("{}_元素异常截图_".format(comment))
        LogUtils.info('---用例执行完成：%s---', key)


